import React, { useEffect, useRef, useState } from 'react';
import TableDataBlock from '@/components/TableDataBlock';
import { Tag, Space, Card, notification, Button, Modal, Form } from 'antd';
import { connect, history } from 'umi';
import ManagementForm from './components/ManagementForm';
import { uploadFile } from '@/utils/utils'
import { AdminType } from '@/common/contact';
// import DisabledSetting from './components/DisabledSetting';
import request from 'axios';
import './index.less';
const enterpriseManagement = (props) => {
  const { dispatch, organizationAuthAdminList, loading, departmentNewList } = props;
  const childRef = useRef();
  const { location = {} } = history
  const { query = {} } = location
  const { accessId } = query
  const [visible, setVisible] = useState(false);
  const [searchParams, setSearchParams] = useState({})
  const [roleList, setRoleList] = useState([]);
  useEffect(() => {
    dispatch({
      type: 'system/fetchListDepartment',
    });
    fetchRoleList();
  }, []);
  const fetchRoleList = (flag) => {
    dispatch({
      type: 'system/fetchRole',
      callback: (e) => {
        const { selfRoleList = [], detaultRoleList = [] } = e;

        setRoleList([...selfRoleList, ...detaultRoleList]);
      },
    });
  };
  const findParentIds = (data, childId, result = []) => {
    for (let i = 0; i < data.length; i++) {
      const item = data[i];
      if (item.id === childId) {
        result.push(item.id);
        if (item.parentDepartmentId) {
          findParentIds(data, item.parentDepartmentId, result);
        }
        break;
      } else if (item.subDepartmentList) {
        findParentIds(item.subDepartmentList, childId, result);
        if (result.length > 0 && item.id) {
          result.push(item.id);
          break;
        }
      }
    }
    return result;
  };
  const filterArray = (list) => {
    let arr = [];
    list.split(',').forEach((item) => {
      arr.push(
        findParentIds(departmentNewList, Number(item))
          .filter((item) => {
            if (item && item !== undefined) {
              return true;
            }
          })
          .reverse(),
      );
    });
    return arr;
  };
  const importUserExcelTemplate = () => {
    dispatch({
      type: 'system/fetchImportAdminExcelTemplate',
      callback: (e) => {
        uploadFile(e.url)
      }
    })
  }

  const importUserList = () => {
    dispatch({
      type: 'system/fetchExportAdmin',
      payload: {
        ...searchParams
      },
      callback: (e) => {
        uploadFile(e.url)
      }
    })
  }

  const filterList = (list) => {
    return list.map((item) => {
      const { departmentName: label, id: value, subDepartmentList: children } = item;
      const localItem = {
        label,
        value,
        children: children ? filterList(children) : undefined,
      };
      return localItem;
    });
  };

  const extraBtn = [
    {
      text: '新增',
      onClick: () => {
        setVisible({
          show: true,
          detail: {
            adminType: "employee",
          }
        });
      },
    },
    {
      text: '导出员工',
      onClick: () => {
        importUserList()
      },
    },
  ];
  const searchItems = [
    {
      label: '用户姓名或手机',
      name: 'keyword',
    },
    // {
    //   label: '角色查询',
    //   name: 'roleId',
    //   select: roleList,
    //   fieldNames: {
    //     label: 'roleName',
    //     value: 'id',
    //   },
    //   type: 'select',
    // },
    {
      label: '部门',
      name: 'departmentId',
      type: 'cascader',
      changeOnSelect: true,
      select: filterList(departmentNewList),
    },
    {
      label: '状态',
      name: 'status',
      select: {
        0: '禁用',
        1: '启用',
      },
      type: 'select',
    },

  ];
  const getColumns = [
    {
      title: '姓名',
      dataIndex: 'username',
    },
    {
      title: '手机',
      dataIndex: 'mobile',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '部门名称',
      dataIndex: 'departmentName',
    },
    {
      title: '岗位类型',
      dataIndex: 'adminType',
      render: (e) => {
        return AdminType[e];
      },
    },
    {
      title: '角色',
      dataIndex: 'roleNames',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (e) => {
        return {
          0: '禁用',
          1: '启用',
        }[e];
      },
    },
    {
      type: 'handle',
      width: 200,
      dataIndex: 'id',
      render: (val, record) => [
        {
          type: 'edit',
          title: '编辑',
          click: () => {
            dispatch({
              type: 'system/fetchAdminDetail',
              payload: { id: val, action: 'update' },
              callback: (e) => {
                const { admin = {}, roleList = [], nextAdmin
                  = {} } = e;
                const {
                  departmentId,
                  mobile,
                } = admin;
                setVisible({
                  show: true,
                  type: 'update',
                  detail: {
                    ...admin,
                    account: mobile,
                    departmentId: findParentIds(
                      departmentNewList,
                      departmentId,
                    ).filter((item) => {
                      if (item && item !== undefined) {
                        return true;
                      }
                    })
                      .reverse(),
                  },
                  roleList: [...roleList].filter((item) => {
                    return item.checkFlag === '1';
                  }),
                });
              },
            });
          },
        },

        {
          title: '禁用',
          visible: record.status === '1',
          click: () => {

            dispatch({
              type: 'system/fakeDisableAdmin',
              payload: { id: val },
              callback: (e) => {
                handleCallback();
              },
            });
          },
        },

        {
          title: '启用',
          visible: record.status === '0',
          click: () => {
            dispatch({
              type: 'system/fakeEnableAdmin',
              payload: { id: val },
              callback: (e) => {
                handleCallback();
              },
            });
          },
        },
      ],
    },
  ];
  const inputFile = async () => {
    const options = {
      types: [
        {
          description: 'Excel Files',
          accept: {
            'application/vnd.ms-excel': ['.xls'],
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx']
          }
        }
      ],
      multiple: false
    };

    try {
      window.showOpenFilePicker(options).then(async val => {
        const [fileHandle] = val
        fileHandle.getFile().then(data => {
          const formData = new FormData();
          formData.append('file', data);
          formData.append('token', window.localStorage.getItem('token'));
          request.post(APIURL + '/auth/admin/importAdmin', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              appType: 'organization',
              device: 'admin',
              Accept: 'application/json',
            },
          }).then(val => {
            const { data = {},
            } = val
            const { resultCode, resultDesc, content = {} } = data
            console.log(data)
            if (resultCode === '1') {
              const { url } = content
              Modal.confirm({
                title: '导入结果',
                content: '用户导入已完成，点击下载查看导入结果',
                okText: '下载',
                onOk() {
                  uploadFile(url)
                },
                onCancel() {
                  console.log('Cancel');
                },
              })
              handleCallback()
            }
            else {
              notification.error({
                message: `请求错误`,
                description: resultDesc,
              });
            }

          })
        })

      })
    } catch (error) {
      // 处理错误
      console.log(error)
    }
  }
  const handleCallback = () => {
    childRef.current.fetchGetData();
  };
  return (
    <Card title='员工列表' extra={<Space>
      <Button type='link' onClick={() => inputFile()}>导入员工</Button>
      <Button type='link' onClick={() => importUserExcelTemplate()}>下载导入模板</Button>
    </Space>}>
      <TableDataBlock
        btnExtra={extraBtn}
        searchCallback={(e) => setSearchParams(e)}
        searchItems={searchItems}
        cRef={childRef}
        loading={loading}
        searchShowData={{ status: '1' }}
        noCard={true}
        columns={getColumns}
        rowKey={(record) => `${record.id}`}
        dispatchType="system/fetchSearchAdmin"
        handleCallback={handleCallback}
        {...organizationAuthAdminList}
      ></TableDataBlock>
      <ManagementForm
        handleCallback={handleCallback}
        visible={visible}
        onClose={() => setVisible(false)}
      ></ManagementForm>
    </Card>
  );
};
export default connect(({ system, loading, }) => ({
  ...system,
  loading: loading.models.system || loading.effects['setting/fakeExportAdminStageData'],
}))(enterpriseManagement);
